import os from 'os';
import Result from './result.js';

// Get local IP address
export function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];

    for (const alias of iface) {
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
  return '127.0.0.1';
}

// Error handler
export function errorHandler (err, req, res, next) {
  console.error("Global error handler:", err);
  // If err is of string type, then return a custom error message.
  if (typeof err === 'string') {
    return Result.error(res, err);
  }
  const code = err.code || Result.ERROR_CODE;
  const message = err.message || Result.INTERNAL_SERVER_ERROR_MESSAGE;
  Result.error(res, message, code);
};